<template>
  <div class="el-main">
    <el-form ref="form" :model="img" label-width="120px">
      <el-form-item label="图片主题" prop="name">
        <el-input v-model="img.name"></el-input>
      </el-form-item>

      <el-form-item label="图片">
        <el-upload
          :action="posterUrl"
          :before-upload="beforeUpload"
          :limit="1"
          :http-request="(params)=>uploadImage(params)"
          :on-remove="(file, fileList)=>removeImage(file, fileList)"
          list-type="picture"
          accept="image/*">
          <el-button size="small">选择图片</el-button>
        </el-upload>
        <img v-show="this.img.photo!==''" :src="this.imgUrl+'/'+img.photo.split('/')[3]" width="135"
             height="201"/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="exit()">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {uploadImgToBase64} from '@/utils/fileUtils'
  import Qs from 'qs';

  export default {
    name: "imageAdd",
    data() {
      return {
        parentId: 0,
        //options: [],
        departmentList: [],
        fileList: [],
        departmentId: '',
        posterUrl: '',
        imgUrls: [],
        imgWidth: '320',
        imgHeight: '400',
        imgBroadcastList: [], // 储存选中   的图片列表
        img: {
          name: "",
          type: "3",
          photo: ''
        }
      }
    },
    methods: {
      handleChange(value) {
        console.log(value);
      },

      // 级联关系
      /*     getMenus: function () {
               let data = Qs.stringify({parentId: this.parentId})
               this.instance.post('/w/departments/departmentMenus', data
               ).then(data => {
                   let menus = data.data;
                   if (this.parentId === 0) {
                       this.options = menus;
                   }
               })
           },*/
      onSubmit() {
        let that = this;
        this.img.type='3';
        this.instance.post('/w/images/createEnvirImg', this.img)
          .then(function (response) {
            that.$router.push({name: 'environment'})
          })
          .catch(function (error) {
            console.log(error);
          });
      },
      beforeUpload(file) {
        let _this = this;
        let _checkSize = false; //是否需要指定上传图片的尺寸
        if (file.size > 1024 * 2000) { //大小超过500kb
          _this.$message.error('图片太大，请重新选择');
          return false;
        }
        const isSize = new Promise((resolve, reject) => {
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.onload = function () {
            if (!_checkSize || (_checkSize && img.width == _this.imgWidth && img.height == _this.imgHeight)) {
              resolve();
            } else {
              reject();
            }
          }
          img.src = _URL.createObjectURL(file);
        }).then(() => {
          return file;
        }, () => {
          _this.$message.error('图片尺寸不对，请重新选择');
          return Promise.reject();
        });
        return isSize;
      },

      uploadImage(params) {

        let uploadData = new FormData();
        uploadData.append('file', params.file);
        let config = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        };
        this.uploadPoster('homed' + new Date().getTime() + '/' + params.file.name, uploadData, config)

      },

      removeImage(file, fileList) {
        console.log(fileList);
      },

      uploadPoster(url, obj, config) {
        let that = this;
        let poster_upload_path = "/w/doctors/upload";
        debugger
        that.instance.post(poster_upload_path, obj, config).then(function (res) {
          console.log(res)
          that.img.photo = res[0].url;
        })

      },
      exit() {
        this.$router.push({name: 'environment'}) // 只能用 name
      },
      findById() {
        let that = this;
        this.instance.get('/w/images/' + that.img.id)
          .then(function (response) {
            that.img=response.data;
          })
          .catch(function (error) {
            console.log(error);
          });
      },
    },

    mounted() {
      let that = this;
      if(!!that.img.id ){
        this.findById();
      }
    },
    created() {
      let that = this;
      if (!!that.$route.query.id) {
        that.img.id = that.$route.query.id
      }
    }
  }
</script>

<style scoped lang="scss">

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
